package com.hsmpay.qian4.service.ds.impl;

import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.account.scanCodePay.MD5;
import com.hsmpay.mobile.action.account.scanCodePay.ScanCodePayParam;
import com.hsmpay.mobile.action.account.scanCodePay.SignUtils;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.service.ds.JQSDKPayService;
import com.hsmpay.utils.DesUtil;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.system.ConConfig;
import javapns.org.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("ds_JQSDKPayService")
public class JQSDKPayServiceImpl implements JQSDKPayService {

    public static WriteFile wf = new WriteFile("ds_JQSDK");
    private static Logger log = LoggerFactory.getLogger(JQSDKPayServiceImpl.class);
    private static final String version = "1.0.0";
    private static final String requestIp = "127.0.0.1";//请求方公网IP
    public static String urlStr = ConConfig.getAttribute("URL_OFFICIAL");
    private static final String customer_no = ConConfig.getAttribute("JQ_SDK_PAY_CUSID");
    private static final String MD5Key = ConConfig.getAttribute("JQ_SDK_PAY_MD5KEY");

    /**
     * 获取支付信息
     * @param scanCodePayParam
     * @return
     * @throws Exception
     */
    public PurchaseResult getPayInfo(ScanCodePayParam scanCodePayParam) throws Exception {

        String notifyUrl = "http://"+urlStr+"/proOneMobile/JQNotify.action";
        String reqUrl = "http://app.1spay.com/agent/transReq.action";

        String outTradeNo = scanCodePayParam.getOutTradeNo();
        double totalFee = Double.valueOf(scanCodePayParam.getTotalFee());

        log.info("【进钱-收款 请求参数】outTradeNo: "+ outTradeNo);
        log.info("【进钱-收款 请求参数】totalFee: "+ totalFee);

        wf.log("【进钱-收款 请求参数】outTradeNo: "+outTradeNo, "调试");
        wf.log("【进钱-收款 请求参数】totalFee: "+totalFee, "调试");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(date);
        String reqDate = dateStr.substring(0,8);
        String reqTime = dateStr.substring(8);

        SortedMap<String,String> map = new TreeMap<>();
        map.put("version", version);
        map.put("service","0004");//进钱微信SDK支付
        map.put("reqDate", reqDate);
        map.put("transAmount", String.valueOf(NumberUtil.roundF2(totalFee*100).longValue()));//金额转为分
        map.put("bgReturnUrl", notifyUrl);
        map.put("customerNo", customer_no);

        map.put("externalId", outTradeNo);
        map.put("requestIp", requestIp);
        map.put("reqTime", reqTime);
        map.put("description", scanCodePayParam.getBody());
        map.put("selfData",DesUtil.generate32Key());

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + MD5Key, "utf-8");
        map.put("sign", sign);

        JSONObject jsonObject = new JSONObject(map);
        log.info("【进钱-SDK收款 请求参数】:" + jsonObject.toString());

        Map<String, String> resultMap = new HashMap<>();

        wf.log("【进钱-SDK收款】请求环境:生产环境", "调试");

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            HttpPost httpPost = new HttpPost(reqUrl);
            StringEntity entityParams = new StringEntity(jsonObject.toString(), "utf-8");
            httpPost.setEntity(entityParams);
            client = HttpClients.createDefault();
            response = client.execute(httpPost);
            if (response != null && response.getEntity() != null) {
                JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity()));
                log.info("【进钱-SDK收款 响应参数】:" + jsonObj.toString());
                Iterator<String> nameItr = jsonObj.keys();
                while (nameItr.hasNext()) {
                    String name = nameItr.next();
                    resultMap.put(name, jsonObj.getString(name));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("【进钱-SDK收款】 系统异常!");
        }

        PurchaseResult pr = new PurchaseResult();
        pr.setReqMsg("获取交易订单失败,请稍后再试!");
        pr.setStatus(0);
        pr.setReqCode("0001");

        if(resultMap.isEmpty()){
            return pr;
        }

        String code = resultMap.get("code");

        if(code.equals("0")){
            pr.setAppId(resultMap.get("appId"));
            pr.setTokenId(resultMap.get("tokenId"));
            pr.setCustomerNo(customer_no);
            pr.setReqMsg("获取交易订单成功!");
            pr.setReqCode("0000");
        }else {
            String message = resultMap.get("message");
            pr.setReqMsg(message);
        }
        return pr;
    }
}
